﻿
using System;
using SqlSugar;
using System.Collections.Generic;
using Mapster;
using Yitter.IdGenerator;
using System.Text;
using System.Linq;
using PARK.Dependency;
using PARK.Consumer.Entity;
using PARK.Common.Core.Manager;
using PARK.System.Interfaces.System;
using WeChat.Api.Model.Close;
using System.Net.Http;
using WeChat.Api.Common;
using System.Threading.Tasks;
using PARK.Common.WeChat.Pay.Model.Close;
using JNPF.Logging;

namespace PARK.Consumer
{
    /// <summary>
    /// 成绩处理
    /// 版 本：V3.2
    /// </summary>
    public class ConsumRefundRepository : IConsumRefundRepository, ITransient
    {
        private readonly ISqlSugarRepository<ConsumRefundEntity> _consumRefundRepository;
        private readonly SqlSugarScope _db;
        private readonly IUserManager _userManager;
        private readonly ISysConfigService _sysConfigService;


        /// <summary>
        /// 初始化一个<see cref="ConsumRefundRepository"/>类型的新实例
        /// </summary>
        public ConsumRefundRepository(
            ISqlSugarRepository<ConsumRefundEntity> consumRefundRepository,
            IUserManager userManager,
            ISysConfigService sysConfigService)
        {
            _consumRefundRepository = consumRefundRepository;
            _db = _consumRefundRepository.Context;
            _userManager = userManager;
            _sysConfigService = sysConfigService;
        }

        /// <summary>
        /// 执行退款
        /// </summary>
        /// <param name="_Refund"></param>
        /// <returns></returns>
        public async Task<ReturnAmount> RefundOrder(RefundModel _Refund)
        {
            //申请退款
            var req = new ApplyAmount
            {
                out_refund_no = _Refund.OutRefundNo,//本次退款单号(就餐平台)
                out_trade_no = _Refund.OutTradeNo,//当前退款的订单号。（比如你下单有个订单号，那退款是不是也要有自己的订单号）
                reason = "退还余额",
                notify_url = "https://jcptapi.xaykt.com/api/wechat/WxPay/RefundCallback", //退款通知
                amount = new RefundsAmountModel
                {
                    refund = _Refund.RefundFee,
                    total = _Refund.TotalFee,
                    currency = "CNY"
                }
            };
            try
            {
                new LoggEx().Info("执行退款:对象->" + req.ToJson());
                var url = $"https://api.mch.weixin.qq.com/v3/refund/domestic/refunds";
                var client = new HttpClient(new HttpHandler());
                var bodyJson = new StringContent(req.ToJson(), Encoding.UTF8, "application/json");
                var resp = await client.PostAsync(url, bodyJson);
                var respStr = await resp.Content.ReadAsStringAsync();
                new LoggEx().Info("执行退款提交,返回->" + respStr);
                var payModel = respStr.ToObject<ReturnAmount>();
                //更新任务状态
                UpdateOrderreFundStatus(_Refund.taskId, payModel);
                return payModel;
            }
            catch(Exception ex)
            {
                new LoggEx().Info("执行退款:异常->" + ex.Message);
                return null;
            }
        }
        /// <summary>
        /// 更新退款任务状态
        /// </summary>
        /// <param name="_taskId"></param>
        /// <param name="payModel"></param>
        /// <returns></returns>
        int UpdateOrderreFundStatus(string _taskId, ReturnAmount payModel)
        {
            try
            {
                if (!string.IsNullOrEmpty(payModel.status))
                {
                    var Paras = new List<SugarParameter>();
                    Paras.Add(new SugarParameter("@OrderId", _taskId));
                    Paras.Add(new SugarParameter("@out_refund_no", payModel.out_refund_no));
                    Paras.Add(new SugarParameter("@refund_id", payModel.refund_id));
                    Paras.Add(new SugarParameter("@refundStatus", payModel.status));
                    Paras.Add(new SugarParameter("@refundAmt", payModel.amount.payer_refund));
                    Paras.Add(new SugarParameter("@upflag", null, true));
                    _db.Ado.UseStoredProcedure().ExecuteCommand("P_PayRefund_Status", Paras);
                    object _obj = Paras[5].Value;
                    if (_obj != null)
                        return int.Parse(_obj.ToString());
                    else
                        return 0;
                }
                else
                {
                    return 0;
                }
            }
            catch(Exception ex)
            {
                return 0;
            }
        }
    }
}
